package com.thingsgrid.appmanager.service.impl;

import ch.ethz.ssh2.Connection;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.thingsgrid.appmanager.entity.ApplicationInfo;
import com.thingsgrid.appmanager.entity.SystemSetting;
import com.thingsgrid.appmanager.mapper.IAppStoreMapper;
import com.thingsgrid.appmanager.service.IAppStoreService;
import com.thingsgrid.appmanager.util.FileProcess;
import com.thingsgrid.appmanager.util.ShellProcessor;
import com.thingsgrid.common.constant.CommonConstant;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@AllArgsConstructor
public class IAppStoreServiceImpl extends ServiceImpl<IAppStoreMapper, SystemSetting> implements IAppStoreService {
	private IAppStoreMapper mapper;


	@Override
	public Map<String, Object> getApp(Page<ApplicationInfo> page, String app_name, String shlefDate, String putoffDate, Float version) {
		List<ApplicationInfo> applicationInfo = mapper.getApp(page,app_name, shlefDate, putoffDate, version);
		Map<String ,Object> returnmap = new HashMap();
		List<Map<String, Object>> returnlist = new ArrayList<>();
		returnmap.put("total",page.getTotal());
		for (ApplicationInfo app : applicationInfo) {
			Map<String, Object> map = new HashMap<>();
			int downtimes = mapper.downloadNum(app.getId());
			map.put("app", app);
			map.put("downloadtimes", downtimes);
			returnlist.add(map);
		}
		returnmap.put("appInfo",returnlist);
		return returnmap;
	}

	/**
	 * 说明：新增应用信息
	 *
	 * @author lilongfei
	 * @since 2019/8/22 15:13
	 */
	@Override
	public Integer insertApplication(ApplicationInfo applicationInfo, MultipartFile file) {
		int result = 1;
		try {
			if (!file.isEmpty()) {
				//文件上传
				String fileUploadUrl = FileProcess.fileUpload(file,applicationInfo.getApplicationName());
				if (fileUploadUrl == null) {
					throw new Exception("文件上传失败");
				} else {
					//生成Dockerfile
					boolean uploadResult = FileProcess.splitDockerfileContent(applicationInfo.getDockerfileContent());
					if (uploadResult) {
						//将size转成MB
						float size = (file.getSize()) / 1024 / 1024;
						applicationInfo.setFileUrl(fileUploadUrl);
						applicationInfo.setFileSize(size);
						applicationInfo.setApplicationStats(1);
						result = mapper.insertApplication(applicationInfo);
						if(result>0){
							//将应用打成镜像并上传至镜像仓库
							String dockerImageName = CommonConstant.HARBOR_IP+"/"+applicationInfo.getApplicationName()+":"
								+applicationInfo.getVersion();
							String buildImage="docker build -t "+ dockerImageName+" .;docker push "+dockerImageName;
							ShellProcessor shellProcessor = ShellProcessor.getInstance();
							Connection connection = shellProcessor.login();
							String cmdResult = shellProcessor.execmd(connection,buildImage);
							log.info("命令执行结果：",cmdResult);
						}else{
							log.error("APP新增失败");
							//新增失败后将文件删除
							String deleteCmd = "rm -r /tmp/"+applicationInfo.getApplicationName();
							ShellProcessor shellProcessor = ShellProcessor.getInstance();
							Connection connection = shellProcessor.login();
							String cmdResult = shellProcessor.execmd(connection,deleteCmd);
							log.info("命令执行结果：",cmdResult);
						}
					} else {
						//上传失败后将文件删除
						String deleteCmd = "rm -r "+fileUploadUrl;
						ShellProcessor shellProcessor = ShellProcessor.getInstance();
						Connection connection = shellProcessor.login();
						String cmdResult = shellProcessor.execmd(connection,deleteCmd);
						log.info("命令执行结果：",cmdResult);
						result = 2;
					}
				}
			} else {
				throw new Exception("文件为空");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}


}
